<template>
  <div>
    <!-- <h3>添加SKU时需要用到的页面结构</h3> -->
    <el-form label-width="100px">
      <el-form-item label="SKU名称">
        <el-input placeholder="SKU名称" v-model="anObjectBeUsedToStoreSkuInformation.skuName"></el-input>
      </el-form-item>
      <el-form-item label="价格（元 ）">
        <!-- 注：“type="number"”表示将文本框的类型设置为“计数器”（即文本框中有带“上、下箭头”的按钮，可以增减数字）↓ -->
        <el-input type="number" placeholder="价格（元）" v-model="anObjectBeUsedToStoreSkuInformation.price"></el-input>
      </el-form-item>
      <el-form-item label="重量（克）">
        <el-input type="number" placeholder="重量（克）" v-model="anObjectBeUsedToStoreSkuInformation.weight"></el-input>
      </el-form-item>
      <el-form-item label="SKU描述">
        <el-input type="textarea" placeholder="SKU描述" v-model="anObjectBeUsedToStoreSkuInformation.skuDesc"></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <!-- 注：此处再放置了一个“行内表单”↓ -->
        <el-form inline>
          <el-form-item v-for="(item, index) in anArrayBeUsedToStorePlatformAttributes" :key="item.id"
            :label="item.attrName">
            <el-select v-model="item.platformAttributeIdAndPlatformAttributeValueId">
              <!-- <el-option label="256GB"></el-option>
              <el-option label="256GB"></el-option>
              <el-option label="256GB"></el-option>
              <el-option label="256GB"></el-option> -->
              <el-option :value="`${item.id}:${attributeValue.id}`"
                v-for="(attributeValue, index) in item.saleAttrValueList" :key="attributeValue.id"
                :label="attributeValue.valueName"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form inline>
          <el-form-item :label="item.saleAttrName" v-for="(item, index) in saleAttributesList" :key="item.id">
            <el-select v-model="item.saleAttributeIdAndSaleAttributeValueId">
              <!-- <el-option label="256GB"></el-option>
              <el-option label="256GB"></el-option>
              <el-option label="256GB"></el-option>
              <el-option label="256GB"></el-option> -->
              <el-option :value="`${item.id}:${saleAttributeValue.id}`"
                v-for="(saleAttributeValue, index) in item.saleAttrValueList" :key="saleAttributeValue.id"
                :label="saleAttributeValue.saleAttrValueName"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片名称">
        <el-table border :data="imageList" ref="aRefForTable">
          <el-table-column type="selection" width="80px" align="center"></el-table-column>
          <el-table-column label="图片" align="center">
            <template #default="{ row, $index }">
              <img :src="row.imgUrl" alt="图片地址已失效" style="width: 100px;height: 100px;" />
            </template>
          </el-table-column>
          <el-table-column label="名称" align="center" prop="imgName"></el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="{ row, $index }">
              <el-button type="primary" size="small" @click="handlerForUserClickSetDefaultImageButton(row)">设置默认</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <div class="confirmAndCancelButtonIAtTheBottomOfTheForm">
          <el-button type="primary" size="default" @click="handlerForUserClickTheSaveButton">保存</el-button>
          <el-button type="default" size="default" @click="handlerForUserClickTheCancelButton">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup name="SkuForm">
import { ref, reactive } from 'vue'
import type {
  typeOfObjectThatRepresentsAnSpu,
  typeOfObjectThatRepresentsAnSaleAttribute,
  typeOfObjectThatStoresInformationAboutTheImageOfAnSpu,
  typeOfObjectThatRepresentsAnSku,
} from '@/api/product/spu/type'
import { requestAttrAndItsValue } from '@/api/product/attr'
import { requestTheSalesAttributeOfASpu, requestTheImageListOfAProductThatBelongsToASpecificCategory3AndIsOnSaleNow, requestAddANewSku } from '@/api/product/spu'
let emit = defineEmits(['changeScene'])
let anArrayBeUsedToStorePlatformAttributes = ref<any[]>([]) // 注：定义一个数组，它被用于存储“平台属性”
let saleAttributesList = ref<typeOfObjectThatRepresentsAnSaleAttribute[]>([]) // 定义一个数组，它被用于存储“销售属性”
let imageList = ref<typeOfObjectThatStoresInformationAboutTheImageOfAnSpu[]>([]) // 定义一个数组，它被用于存储“图片列表”
let anObjectBeUsedToStoreSkuInformation = reactive<typeOfObjectThatRepresentsAnSku>({ // 定义一个对象，它被用于存储SKU的信息
  spuId: '',
  tmId: '', // 品牌ID
  category3Id: '',
  skuAttrValueList: [ // 此处定义一个数组，它被用于存储“SKU属性值”（即平台属性值）
    {
      attrId: '',
      valueId: '',
    }
  ],
  skuSaleAttrValueList: [ // 此处定义一个数组，它被用于存储“SKU销售属性值”
    {
      saleAttrId: '',
      saleAttrValueId: '',
    }
  ],
  price: '',
  skuName: '',
  skuDesc: '', // sku的描述信息
  weight: '', // sku的重量信息
  skuDefaultImg: '', // sku的默认图片的网址
})
let aRefForTable = ref<any>() // 获取表格组件的实例对象
/**
 * @description: 函数“handlerForUserClickTheSaveButton”被用于处理用户点击“保存”按钮时发生的事件
 */
async function handlerForUserClickTheSaveButton() {
  // 整理数据↓
  // 整理平台属性↓
  let platformAttributeList = anArrayBeUsedToStorePlatformAttributes.value.reduce((prev: any, next: any) => {
    if (next.platformAttributeIdAndPlatformAttributeValueId) {
      let [attrId, valueId] = next.platformAttributeIdAndPlatformAttributeValueId.split(':')
      console.log(attrId, valueId)
      prev.push({ attrId, valueId })
    }
    return prev // 把上次累加后的结果返回，作为reduce函数的返回值
  }, [])
  anObjectBeUsedToStoreSkuInformation.skuAttrValueList = platformAttributeList
  // 整理销售属性↓
  anObjectBeUsedToStoreSkuInformation.skuSaleAttrValueList = saleAttributesList.value.reduce((prev: any, next: any) => {
    if (next.saleAttributeIdAndSaleAttributeValueId) {
      let [saleAttrId, saleAttrValueId] = next.saleAttributeIdAndSaleAttributeValueId.split(':')
      prev.push({ saleAttrId, saleAttrValueId })
    }
    return prev
  }, [])
  // 发送添加SKU的请求↓
  let result: any = await requestAddANewSku(anObjectBeUsedToStoreSkuInformation)
  console.log(result)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: "添加SKU成功" })
    emit('changeScene', { flag: 'aDivElementIncludeTable', params: '' })
  } else {
    ElMessage({ type: 'error', message: "添加SKU失败" })
  }
}
/**
 * @description: 函数“handlerForUserClickTheCancelButton”被用于处理用户点击“取消”按钮时发生的事件
 */
function handlerForUserClickTheCancelButton() {
  emit('changeScene', { flag: 'aDivElementIncludeTable', params: '' }) // 注：此处之所以没有传参数“params”，是因为“无需发送请求”
}
/**
 * @description: 函数“ initDataOfTheSku”被用于初始化SKU的数据
 */
async function initDataOfTheSku(category1Id: number, category2Id: number, spu: typeOfObjectThatRepresentsAnSpu) {
  // 收集数据↓
  anObjectBeUsedToStoreSkuInformation.category3Id = spu.category3Id
  anObjectBeUsedToStoreSkuInformation.spuId = spu.id
  anObjectBeUsedToStoreSkuInformation.tmId = spu.tmId

  console.log("初始化添加SKU的表单中需要用到的数据的函数被调用了")
  console.log(category1Id, category2Id, spu)
  // 注：此处调用API，以获取“平台属性”和“销售属性”，以及“某个产品的图片列表”↓
  let result: any = await requestAttrAndItsValue(category1Id, category2Id, spu.category3Id)
  console.log(result) // {code: 200, message: '成功', data: Array(29), ok: true}
  let anotherResult: any = await requestTheSalesAttributeOfASpu(spu.id)
  console.log(anotherResult)
  let theThirdResult = await requestTheImageListOfAProductThatBelongsToASpecificCategory3AndIsOnSaleNow(spu.id)
  console.log(theThirdResult)
  // 存储数据↓
  anArrayBeUsedToStorePlatformAttributes.value = result.data
  saleAttributesList.value = anotherResult.data
  imageList.value = theThirdResult.data
}
/**
 * @description: 函数“handlerForUserClickSetDefaultImageButton”被用于处理用户点击设置默认图片按钮时发生的事件
 */
function handlerForUserClickSetDefaultImageButton(row: typeOfObjectThatStoresInformationAboutTheImageOfAnSpu) {
  console.log(row)
  // 注：方法“toggleRowSelection”被用于用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则可直接设置这一行选中与否↓
  // 为避免产生“多行数据同时被选中”的情况，此处先将表格中的所有行都设置为“未选中”状态↓
  imageList.value.forEach((item: typeOfObjectThatStoresInformationAboutTheImageOfAnSpu) => {
    aRefForTable.value.toggleRowSelection(item, false)
  })
  aRefForTable.value.toggleRowSelection(row, true) // 用户选中的图片所在行会被设置为“选中”状态
  anObjectBeUsedToStoreSkuInformation.skuDefaultImg = row.imgUrl
  console.log(aRefForTable.value)
}
defineExpose({ initDataOfTheSku }) // 对外导出方法，以供父组件调用
</script>

<style scoped>
.confirmAndCancelButtonIAtTheBottomOfTheForm {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>